package flex.cc.order.manage.service.impl;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.base.dto.LoginAuthDto;
import flex.cc.base.exception.BusinessException;
import flex.cc.basicinformation.entity.ChannelDataEntity;
import flex.cc.basicinformation.entity.ChannelEntity;
import flex.cc.basicinformation.service.ChannelService;
import flex.cc.common.Constants;
import flex.cc.common.utils.HttpClientUtil;
import flex.cc.core.utils.RequestUtil;
import flex.cc.order.manage.dao.OrderTrackDao;
import flex.cc.order.manage.dto.order.OrderTrackEntity;
import flex.cc.vehicle_svr.model.UpLoadImageModel;

/**
 * 
 * @author WANGCONG
 * 2021年9月13日下午1:42:39
 * @desc 服务单图像回传上游
 */
@Service
public class UploadImgService {

	private static final Logger logger = LoggerFactory.getLogger(UploadImgService.class);
	
	/** 回传图片接口参数 */
	public static final String CHANNEL = "ZXHY";
	/** 回传图片接口参数 */
	public static final String KEY = "CSHAPPZX";
	
//	public static final String IMAGE_CALLBACK_URL = "https://carlifecenter.sinosig.com/suncar-card/thirdApi/syncPhotoInfo";
//	public static final String IMAGE_CALLBACK_URL = "https://uatcarlife.ygbx.com:9443/suncar-card/thirdApi/syncPhotoInfo";
	@Value("${pengda.synImg}")
    private String synImg;
	@Resource
	private ChannelService channelService;
	@Resource
    private OrderTrackDao orderTrackDao;
	
	/**
	 * 
	 * @author WANGCONG
	 * 2021年9月13日下午1:43:52
	 * @param picUrls 
	 * @desc 图像异步回传上游
	 */
	@Async
    public void uploadImg(String orderNo, UpLoadImageModel imgModel, String ownerOrderNo, List<String> picUrls, String sourceName, String status) {
		Map<String, String> channelMap = new HashMap<>();
		channelMap.put("clientId", sourceName);
		List<ChannelEntity> channelList = channelService.findChannelByParam(channelMap);
		if(channelList.size()==0 || channelList==null){
			System.out.println("未找到渠道商");
		}else{
			String channelId = channelList.get(0).getId().toString();
			List<ChannelDataEntity> channelDataList = channelService.queryListByYwId(channelId);
			String synImg_url = "";
			for(int i=0; i<channelDataList.size(); i++){
	    		if(Constants.synImg.equals(channelDataList.get(i).getUrlType())){
	    			synImg_url = channelDataList.get(i).getUrl();
	    			break;
	    		}
	    	}
			if(PublicUtil.isNotEmpty(synImg_url)){
				Map<String, Object> params = new HashMap<>();
				params.put("customerCode",ownerOrderNo);
				params.put("caseNo",ownerOrderNo);
				params.put("carServiceType","0");
				params.put("tracktype","");
				params.put("picList", picUrls);
				String cshToken = DESEncrypt(params.get("customerCode") + "_" + System.currentTimeMillis() + "_" + CHANNEL, KEY);
				
//				String result = HttpClientUtil.sendHttpPost(synImg_url, JSONObject.toJSONString(params), new HashMap<String, String>(){{
//					put("Content-Type", "application/json;charset=utf-8");
//					put("cshToken", cshToken);
//					put("channel", CHANNEL);
//		        }});
//				logger.info("上游图片回传==>> Body:{}, Result:{}", JSONObject.toJSONString(params), result);
				
				AtomicReference<Integer> counter = new AtomicReference<Integer>(0);
				String temp_code = ""; //记录接口回写的code码，便于轨迹备注插入
				while(counter.get()<3){
					//{"resCode":"SUCCESS","resMsg":"成功"}；
					String result = HttpClientUtil.sendHttpPost(synImg_url, JSONObject.toJSONString(params), new HashMap<String, String>(){{
						put("Content-Type", "application/json;charset=utf-8");
						put("cshToken", cshToken);
						put("channel", CHANNEL);
			        }});
					if (result != null) {
	            		try {
	            			JSONObject resultObj = JSONObject.parseObject(result);
	                        String resCode = PublicUtil.isNotEmpty(resultObj.get("resCode")) ? resultObj.get("resCode").toString() : null; 
	                        temp_code = resCode;
	                        if(PublicUtil.isNotEmpty(resCode) && !"SUCCESS".equals(resCode)){
	                        	counter.compareAndSet(counter.get(), counter.get()+1);
	                        }else{
	                        	counter.getAndSet(5);
	                        }
						} catch (Exception e) {
							counter.getAndSet(5);
						}
	            		logger.info("上游图片回传==>> Body:{}, Result:{}", JSONObject.toJSONString(params), result);
	            	}else {
	            		counter.compareAndSet(counter.get(), counter.get()+1);
	            	}
				}
				if("SUCCESS".equals(temp_code)){//成功
	            	saveTrack(orderNo, "07", "自动图片回传上游成功", status, new Date(), RequestUtil.getLoginUser());
				}else{
					saveTrack(orderNo, "07", "自动图片回传上游失败", status, new Date(), RequestUtil.getLoginUser());
				}
				
			}
		}
    }
	
	private void saveTrack(String orderNo, String trackType, String trackDesc, String status, Date currentDate, LoginAuthDto loginUser){
        // 服务单轨迹表
        OrderTrackEntity orderTrackEntity = new OrderTrackEntity();
        orderTrackEntity.setDataId(UUID.randomUUID().toString().replace("-", ""));
        orderTrackEntity.setOrderNo(orderNo);
        orderTrackEntity.setTrackType(trackType);
        orderTrackEntity.setTrackDesc(trackDesc);
        orderTrackEntity.setStatus(status);
        orderTrackEntity.setIsDelete(0);
        orderTrackEntity.setCreateTime(currentDate);
        orderTrackEntity.setCreater(loginUser.getUserCode());
        orderTrackEntity.setUpdateTime(currentDate);
        orderTrackEntity.setUpdater(loginUser.getUserCode());
        orderTrackDao.insert(orderTrackEntity);
    }
	
	/**
	 * DES 加密
	 * */
	public static String DESEncrypt(String content, String key){
		try{
			Cipher cipher = Cipher.getInstance( "DES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "DES"), 
					new IvParameterSpec(new byte[]{1,2,3,4,5,6,7,8}));
	        return Base64.getEncoder().encodeToString(cipher.doFinal(content.getBytes("UTF8")));
		}catch(Exception e){
			throw new BusinessException("加密错误");
		}
	}
	
}
